// 向量

import { _o } from "./index.js";

// 叉乘 v1 × v2 = |a| * |b| * sin θ
export const crossProduct = ([p1, p2], [p3, p4]) => {
    let v1 = [p1[0] - p2[0], p1[1] - p2[1]]
    let v2 = [p3[0] - p4[0], p3[1] - p4[1]]
    return v1[0] * v2[1] - v1[1] * v2[0];
}

// 判断是凹凸点
// 1凹点  -1凸点
// 1顺时针 0逆时针
// 右手法则 
export const checkConcave = ([p1, p2, p3]) => {
    let v1 = [p1[0] - p2[0], p1[1] - p2[1]]
    let v2 = [p2[0] - p3[0], p2[1] - p3[1]]
    return (v1[0] * v2[1] - v1[1] * v2[0]) >= 0 ? 1 : 0;
}

// 优角（Reflexive Angle
// 1顺时针 0逆时针
export const checkSweepFlag = (points, index) => {
    let len = points.length
    let prev = points[(index - 1) < 0 ? len - 1 : index - 1]
    let curr = points[index]
    let next = points[(index + 1) % len]
    return checkConcave([prev, curr, next])
}
// 多边形 顺逆时针
export const checkPolygonSweepFlag = (points) => {
    let o = _o(points)
    return checkConcave([points[0], o, points[1]])
}

// 凸 (convex) 多边形
// 凹 (concave) 多边形
export const isConcavePolygon = (points) => {
    let len = points.length
    let first = checkSweepFlag(points, 0)
    for (let i = 0; i < len; i++) {
        let curr = points[i]
        let next = points[(i + 1) % len]
        let next2 = points[(i + 2) % len]
        curr = checkConcave([curr, next, next2])
        if (first !== curr) {
            return true
        }
    }
    return false
}

// 移动绝对距离

const toVec = (p1, p2) => {
    return [p1[0] - p2[0], p1[1] - p2[1]]
}

// 对两向量做点乘,若结果大于0,就是同向,等于0垂直,小于0反向
// 如a(x1,y1),b(x2,y2)
// a*b=x1*x2+y1*y2;
// 判断a*b的符号就可可以了
export const oppositeDirection = ([p1, p2], [p3, p4]) => {
    let v1 = toVec(p1, p2)
    let v2 = toVec(p3, p4)
    return v1[0] * v2[0] + v1[1] * v2[1] < 0
}